import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import '../SearchCategory.css';  // 导入CSS文件

const MypageCategory = ({ category, onCategoryChange }) => {
  const navigate = useNavigate();  // 获取 navigate 函数

  const [userId, setUserId] = useState(null); // 新增 userId 状态

  // 获取并设置 userId
  useEffect(() => {
    const storedUserId = localStorage.getItem('userId');
    if (storedUserId) {
      setUserId(storedUserId);
    } 
  }, []);

  const handleCategoryClick = (newCategory, path) => {
    if (!userId) {
      console.error('User ID is not available. Cannot navigate.'); // userId 为空时的错误提示
      return;
    }
    console.log(`Navigating to: ${path}`);  // 在点击时打印跳转路径
    onCategoryChange(newCategory); // 更新父组件中的 category
    navigate(path);  // 使用 navigate 进行页面跳转
  };

  return (
    <div className="mypage-category">
      <ul className="category-list">
        <li 
          className={category === 'topics' ? 'active' : ''} 
          onClick={() => handleCategoryClick('topics', `/mypage/topics/${userId}`)}
        >
          我的收藏
        </li>
        <li 
          className={category === 'likes' ? 'active' : ''} 
          onClick={() => handleCategoryClick('likes',`/mypage/likes/${userId}`)}
        >
          我的点赞
        </li>
        <li 
          className={category === 'following' ? 'active' : ''} 
          onClick={() => handleCategoryClick('following', `/mypage/following/${userId}`)}  
        >
          我的关注
        </li>
        <li 
          className={category === 'followers' ? 'active' : ''} 
          onClick={() => handleCategoryClick('followers', `/mypage/followers/${userId}`)}  
        >
          我的粉丝
        </li>
      </ul>
    </div>
  );
};

export default MypageCategory;
